
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h> /* exit() */
#include <unistd.h> /* close() */
#include <string.h> /* memset() */

#define LOCAL_SERVER_PORT 40000
#define MAX_MSG 1024

int main(int argc, char *argv[]) {
  int sd, rc, n;
  socklen_t cliLen;
  struct sockaddr_in cliAddr, servAddr;
	char *msg, *cidnum, *cidname, *called;

  if((sd=socket(AF_INET, SOCK_DGRAM, 0))<0) {
    printf("%s: cannot open socket \n",argv[0]);
    exit(1);
  }

  servAddr.sin_family = AF_INET;
  servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servAddr.sin_port = htons(LOCAL_SERVER_PORT);

  if((rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr)))<0) {
    printf("%s: cannot bind port %d \n", argv[0], LOCAL_SERVER_PORT);
    exit(1);
  }

  printf("%s: waiting for data on port UDP %u\n", argv[0], LOCAL_SERVER_PORT);
	
	msg = alloca((size_t)MAX_MSG+1);
  while(1) {
    cliLen = sizeof(cliAddr);
    if((n = recvfrom(sd, msg, MAX_MSG, 0, (struct sockaddr *)&cliAddr, &cliLen))<0) {
      printf("%s: cannot receive data \n",argv[0]);
      continue;
    }

		if(strchr(msg,'|')) {
			cidnum  = strsep(&msg, "|");
			cidname  = strsep(&msg, "|");
			called  = strsep(&msg, "\0");
			printf("%s (%s) for %s\n", cidname, cidnum, called);
		} else {
			printf("message received: %s", msg);
			continue;
		}
		
  }
	return 0;
}
